import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import http from "../../http";


const initialState: { value: any } = {
  value: {
    token: "",
    user: {},
    videoUserId: "", 
    visible: false, 
    call: 'caller', // caller (来电者)  recipient (被叫者)
    candidate: "",
    offer: "",
    answer:"",
    noticeId: "",
    webrtc:"voice", // video, voice
  },
};

try {
  const storedUser = localStorage.getItem("user");
  if (storedUser !== null) {
    initialState.value = JSON.parse(storedUser);
  }
} catch (error) {
  console.error('Error initializing user state:', error);
}


export const refreshUserInfo: any = createAsyncThunk('/user/refresh', async () => {
  const response = await http.get("/getCurrentUser");
  const user = response.data;
  return user;
})


export const userSlice = createSlice({
  name: "user",
  initialState,

  extraReducers: (builder) => {
    builder.addCase(refreshUserInfo.fulfilled, (state, action) => {  
      const payload: any = action.payload;
      console.log("刷新的用户",payload);
      const userStr = localStorage.getItem('user');
      if(userStr){
        const user = JSON.parse(userStr);
        user.user = payload
        state.value.user = payload;
        localStorage.setItem('user', JSON.stringify(user));
      }
     
    });
  },

  reducers: {

    setNoticeId:(state,action)=>{
      const {noticeId } = action.payload; 
      state.value.noticeId = noticeId;
    },

    clearVideo:(state,action)=>{
      state.value.candidate = "";
      state.value.offer = "";
      state.value.answer = "";
      state.value.webrtc = "";
    },

    addOffer: (state,action) => {
      state.value.offer = action.payload;
    },
    addAnswer: (state,action) => {
      state.value.answer = action.payload;
    },
    addCandidate: (state,action) => {
      state.value.candidate = action.payload;
    },
    updateVideoUserId: (state, action) => {
      const {videoUserId, visible,call,offer,webrtc} = action.payload; 
      state.value.videoUserId = videoUserId ?? "";
      state.value.visible = visible ?? "";
      state.value.call = call ?? "";
      if(offer){
        state.value.offer = offer;
      }
      if(webrtc){
        state.value.webrtc = webrtc;
      }
    },
    updateUser: (state, action) => {
      localStorage.setItem('user', JSON.stringify(action.payload))
      state.value = action.payload;
    },
  },
})

export const { setNoticeId,clearVideo,addAnswer,addOffer,addCandidate,updateUser,updateVideoUserId } = userSlice.actions;

export default userSlice.reducer